package com.cynen.crawler;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

/**
 * httpPost请求带参数方式测试.
 */

public class HttpPostParamTest {
    public static void main(String[] args) {
        // 基本使用步骤.
        // 1.创建对象.
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 2. 创建post请求
        HttpPost httpPost = new HttpPost("http://yun.itheima.com/search");

        // 声明list集合,封装表单参数.
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // 设置请求参数: keys:java
        params.add(new BasicNameValuePair("keys","java"));

        // 创建表单Entity对象.
        try {
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params,"utf8");
            // 设置表单Entity对象.
            httpPost.setEntity(formEntity);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        CloseableHttpResponse httpResponse = null;
        try {
            // 3.使用httpclient发起请求.
            httpResponse = httpClient.execute(httpPost);
            // 4.解析响应.
            if (httpResponse.getStatusLine().getStatusCode() == 200){
                String content = EntityUtils.toString(httpResponse.getEntity(),"utf8");
                System.out.println(content);
                System.out.println(content.length());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 5.关闭资源.
            try {
                // 关闭响应链接
                httpResponse.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            try {
                // 关闭客户端.
                httpClient.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
}
